package flex.cc.drive.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderDao;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderEntity;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.drive.service.DriverSynStatusService;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.single.service.SingleDriverSynStatusService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2022年1月14日下午14:46:12
 * @desc 代驾状态同步接口
 */
@RestController
@RequestMapping(value = "/storeapi")
public class DriveSynSatusController extends BaseController{
    
//	@Value("${api.config.key}")
//  private String key;
	@Resource
    private DriverSynStatusService driveSynSatusService;
	@Resource
    private SingleDriverSynStatusService singleDriverSynStatusService;
	@Resource
    private ValueAddedServiceProviderDao valueAddedserviceProviderDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;
    @Autowired
    private StoreCouponDao storeCouponDao;
	/**
	 * 
	 * @author WANGCONG
	 * 2022年1月14日下午14:47:36
	 * @desc 状态同步处理
	 */
	@ResponseBody
    @RequestMapping("/synSatus")
    public JSONObject synSatus(HttpServletRequest request) throws Exception{
		JSONObject jsonResult = new JSONObject();
		long startTime = System.currentTimeMillis();
    	logger.info("DriveSynSatusController 代驾状态同步接口:begintime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
    	//状态同步业务处理
    	Boolean flag = true;
        String responseMsg = "成功";
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            logger.info("DriveSynSatusController 代驾状态同步接口接收加密报文： "+requestJson);
            if (requestJson != null && !"".equals(requestJson)) {
            	//获取加密串
            	JSONObject requestBody = JSONObject.parseObject(requestJson);
                Map<String, String> requestBodyMap  = requestBody.toJavaObject(Map.class);
                String encryptData =  requestBodyMap.get("encryptData");
                String apiCode =  requestBodyMap.get("apiCode");//约束之后新服务商要传的唯一识别码
            	
                String provider = "";
                Map<String, Object> params = new HashMap<String, Object>();
            	if(PublicUtil.isEmpty(apiCode)){//盛大的，默认
            		params.put("apiCode", "SD");
            	}else{
            		params.put("apiCode", apiCode);
            	}
            	ValueAddedServiceProviderEntity serviceProviderEntity = valueAddedserviceProviderDao.getOneByParams(params);
        		if(PublicUtil.isNotEmpty(serviceProviderEntity)){
        			provider = String.valueOf(serviceProviderEntity.getId());
        		}else{
        			flag = false;
                    responseMsg = "apiCode信息未配置，请联系业务人员";
                	logger.error("DriveSynSatusController 代驾状态同步接口失败:apiCode信息未配置，请联系业务人员");
        		}
                
                String key = apiConfigUtil.getApiConfig(provider, "drive_decode");
                String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
                
            	String synSatusRequestJson = DriveDESUtil.driverDecrypt(encryptData,key,key3Des);
            	logger.info("DriveSynSatusController 代驾状态同步接口接收解密报文： "+synSatusRequestJson);
                // 调用业务处理 =============================
            	logger.info("storeapi/synSatus requestJson:" + synSatusRequestJson);
                JSONObject synSatusRequestBody = JSONObject.parseObject(synSatusRequestJson);
                Map<String, Object> synSatusRequestBodyMap = synSatusRequestBody.toJavaObject(Map.class);
                //卡券编码
    			String orderId = (String) synSatusRequestBodyMap.get("orderId");
    			if(PublicUtil.isEmpty(orderId)) {
    	    		logger.error("订单编号不能为空");
    	    		// 生成响应报文
    	    		flag = false;
    	    		responseMsg = "订单编号不能为空";
    			}else{
    				//根据卡券编码 获取卡券信息
    				StoreCouponEntity storeCouponEntity = storeCouponDao.queryByCouponNum(orderId);
    				//根据服务包编码 无服务包编码为单项 反之为服务包
    				String packageCode = storeCouponEntity.getPackageCode();
    				flag = true;
    				if(PublicUtil.isEmpty(packageCode)){
    					jsonResult = singleDriverSynStatusService.driverSynStatus(synSatusRequestBodyMap,requestJson); 
    	                logger.info("storeapi/synSatus： "+jsonResult);
    				}else{
    	                jsonResult = driveSynSatusService.driverSynStatus(synSatusRequestBodyMap,requestJson); 
    	                logger.info("storeapi/synSatus： "+jsonResult);
    				}
    			}
                
                
            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("storeapi/synSatus 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("storeapi/synSatus 数据接收异常:" + e.getMessage());
        }
        if(!flag){
        	// 生成响应报文
            jsonResult.put("responseCode", "ERROR");
        	jsonResult.put("responseMsg", responseMsg);
        }
    	long endTime = System.currentTimeMillis();
    	logger.info("DriveSynSatusController 代驾状态同步接口:endtime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")+"; 处理时长="+(endTime - startTime)+"; resJson=?"+jsonResult.toString());
		return jsonResult;
	}
	
}
